<?php


class core_remote_request {
	
	public static $errno = '';
	public static $errstr = '';

	protected static $_socket = null;
	protected static $_buff_size = 4096;

	public static function connect($host, $port = 80, $timeout = 30) {
		self::$_socket = fsockopen($host, $port, self::$errno, self::$errstr, $timeout);
		if (!is_resource(self::$_socket)) {
			die('create connection failed!');
		}
	}

	public static function getResponseBody($res) {
		return trim(substr($res, strpos($res, "\r\n\r\n")));
	}

	public static function getResponseHeader($res) {
		return trim(substr($res, 0, strpos($res, "\r\n\r\n")));
	}

	public static function sendRequest($msg) {
		if (!is_resource(self::$_socket)) {
			die('self::$_socket is not a resource [sendRequest('.$msg.')]');
		}
		
		return fwrite(self::$_socket, $msg);
	}

	public static function getResponse() {
		if (!is_resource(self::$_socket)) {
			die('self::$_socket is not a resource [getResponse()]');
		}
		
		$result = '';
		
		while($line = fgets(self::$_socket, self::$_buff_size)) {
			$result .= $line;
			if($line == "\r\n") {
				break;
			}
		}
		while ($r = fread(self::$_socket,self::$_buff_size)) {
			$result .= $r;
		}
		
		return $result;
	}

	public static function onResponse($response) {
		// empty
	}

	public static function close() {
		if (is_resource(self::$_socket)) {
			return fclose(self::$_socket);
		}
	}

	public static function main($msg2send = '', $host, $port = 80, $timeout = 30) {
		self::connect($host, $port, $timeout);
		self::sendRequest($msg2send);
		$res = self::getResponse();
		self::onResponse($res);
		self::close();
	}
}



?>